package br.usp.pcs.basys.event;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import br.usp.pcs.basys.Job;
import br.usp.pcs.basys.engine.IResources;

public class ReleaseDisk extends ComputerSystemEvent {

	

	public ReleaseDisk(Job job, Date date, IResources resources) {
		super(job, date, resources);
	}

	@Override
	List<ActionResult> run() {
		List<ActionResult> result = new ArrayList<ActionResult>();
		resources.releaseDisk();
		scheduledProcessorRequestAndAdvanceDiskQueue(result);
		return result;
	}

	private void scheduledProcessorRequestAndAdvanceDiskQueue(List<ActionResult> result) {
		Long duration = job.getMeanOverheadTime();
		Date nextEventDate = getDateAfterWaiting(duration);
		
		ComputerSystemEvent nextEvent = new ProcessorRequest(job,nextEventDate,resources);
		resources.add(nextEvent);
		result.add(new ScheduledEventResult(nextEvent));
		
		ActionResult advanceDiskQueue = new ActionResult() {
			public String toString() {
				return "Advance Disk Queue";
			}
		};
		result.add(advanceDiskQueue);
		
		advanceDiskQueue(nextEventDate);
	}

	private void advanceDiskQueue(Date nextEventDate) {
		DiskRequest diskRequest = resources.pollDiskQueue();
		if (diskRequest!=null) {
			diskRequest.setDate(nextEventDate);
			resources.add(diskRequest);
		}
	}

}
